﻿using OperationPlugins.Validators.DataAnnotations;
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace TimeProject.Engine.DbModels
{
    [UsePluginValidators]
    public abstract class EntityBase
    {
        private int _id;

        public event EventHandler<IdAssignedEventArgs> IdAssigned;

        protected EntityBase()
        {
            IsActive = true;
        }

        /// <summary>
        /// ID.
        /// </summary>
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id
        {
            get { return _id; }
            set
            {
                _id = value;
                OnIdAssigned(new IdAssignedEventArgs {Id = value});
            }
        }

        /// <summary>
        /// The username who created this item.
        /// </summary>
        [MaxLength(256)]
        [Required]
        public string Creator { get; set; }

        /// <summary>
        /// Timestamp.
        /// </summary>
        [Required]    
        public DateTime Created { get; set; }

        /// <summary>
        /// The username who modified this item.
        /// </summary>
        [MaxLength(256)]
        public string Modifier { get; set; }

        /// <summary>
        /// Timestamp.
        /// </summary>
        public DateTime? Modified { get; set; }

        /// <summary>
        /// The username who passivated this item.
        /// </summary>
        [MaxLength(256)]
        public string Passivator { get; set; }

        /// <summary>
        /// Timestamp.
        /// </summary>
        public DateTime? Passivated { get; set; }

        /// <summary>
        /// Is active?
        /// </summary>
        public bool IsActive { get; set; }

        public virtual void SoftDelete()
        {
            if (IsActive == false)
            {
                throw new InvalidOperationException("The entity has already been marked as deleted.");
            }

            IsActive = false;
        }

        protected virtual void OnIdAssigned(IdAssignedEventArgs e)
        {
            var l = IdAssigned;
            if (l != null)
            {
                l(this, e);
            }
        }

        public sealed class IdAssignedEventArgs : EventArgs
        {
            public int Id { get; set; }
        }

    }
}
